<template>
  <div class="index">
    <div class="head">
      <div class="logo">
        <span class="iconfont iconnew"></span>
      </div>
      <div class="search" @click="$router.push({name: 'search'})">
        <van-icon name="search" />
        <span>搜索新闻</span>
      </div>
      <div class="user" @click="$router.push({path: `/person/${id}`})">
        <van-icon name="manager" />
      </div>
    </div>
    <!-- nav导航栏思路：
      引入组件，获取列表数据，存到data，渲染， 难点 默认栏目的绑定active
    -->
    <!-- <van-icon name="plus" class="plus"/> -->
    <van-tabs v-model="active" swipeable sticky>
      
      <van-tab :title="item.name" v-for="item in cateList" :key="item.id">
        <!-- 放在栏目里，栏目内容替换van-cell的遍历 在本栏目里增添两个变量loading: false,
        finished: false-->
        
        <van-list
          v-model="item.loading"
          :finished="item.finished"
          finished-text="没有更多了"
          @load="onLoad"
          :immediate-check="false"
          :offset="10"
        >
          <van-pull-refresh v-model="item.isLoading" @refresh="onRefresh">
            <articlecell v-for="article in item.postList" :key="article.id" :post="article"></articlecell>
          </van-pull-refresh>
        </van-list>
      </van-tab>
      <!-- //TODO任务
      1每个栏目的数据不相干，然后需要找个地方存储，存到cateList里，因为里面分了0-20.。栏目，在每个栏目里创建一个数组 
      2此外，查看API文档得知，在获取文章时，需要传递三个参数：栏目id（可以通过active）获得、剩余的两个需要自己定义，pageIndex、pageSize可以在改造数据的时候需要添加上
      3、-->
    </van-tabs>
    
  </div>
</template>

<script>
import { getAllCate } from '../apis/cate.js';
import { getArticle } from '../apis/article.js';
import articlecell from '../components/articlecell.vue';
export default {
  data() {
    return {
      id: '',
      active: localStorage.getItem('this_token') ? 1 : 0, //固定绑定头条
      cateList: [],
      addcateList:[]
    };
  },
  components: {
    articlecell
  },
  async mounted() {
    let id = localStorage.getItem('thisuser_id');
    this.id = id;
    // console.log(id);
    if(localStorage.getItem('hasadded')) {
         this.cateList = JSON.parse(localStorage.getItem('hasadded'))
         if(localStorage.getItem('this_token')) {
           this.cateList.unshift({id:0, name:'关注',is_top: 1},{ 
            id: 999,
            name: '头条',
            is_top: 1
        })
         }else {
           this.cateList.unshift({ 
            id: 999,
            name: '头条',
            is_top: 1
        })
         }
           
         this.addcateList = JSON.parse(localStorage.getItem('canadd'))
     }else {
    let res = await getAllCate();
    // console.log(res);
    // if(res.data.data.length !== 0) {
    this.cateList = res.data.data;
     }
    this.cateList = this.cateList.map(value => {
      return {
        ...value,
        postList: [],
        pageIndex: 1,
        pageSize: 5,
        loading: false,
        finished: false,
        isLoading: false
        // category:this.cateList[this.active].id
      };
    });
    // console.log(this.cateList);
    // console.log(this.cateList[this.active].postList.id);
    this.init();

// 选择伪元素
    let qw = document.querySelector('.van-sticky')
    qw.onclick = (e) => {
      if(e.target.className == 'van-sticky'){
        // console.log(123)
        this.$router.push({name:'cateManage'})
      }
      return false;
    }
  
    // }
  },
  methods: {
    plusCate(e) {
      // console.log(e);
      
    },
    async init() {
      // console.log(this.cateList[this.active],this.active);
      //有了三个参数后 就可以根据栏目获取文章了 不传参则获取所有类型栏目的
      // let res2 = await getArticle()
      // console.log(res2);
      let res2 = await getArticle({
        pageIndex: this.cateList[this.active].pageIndex,
        pageSize: this.cateList[this.active].pageSize,
        category: this.cateList[this.active].id
      });
      //       console.log(this.cateList[this.active]);
      //         let res2 = await getArticle(this.cateList[this.active])
      // todo 多页时 不应该覆盖 要push
      this.cateList[this.active].postList.push(...res2.data.data);
      //         console.log(this.cateList[this.active].postList);
      // 当页数据请求完成后 手动修改loading和finished的值
      if(this.cateList[this.active].loading) this.cateList[this.active].loading = false;
      if(this.cateList[this.active].isLoading) this.cateList[this.active].isLoading = false;
      if (res2.data.data.length < this.cateList[this.active].pageSize) {
        this.cateList[this.active].finished = true;
        this.cateList[this.active].loading = false;
      }
      //
    },
    //
    //   onClick() {
    //       console.log(this.active);
    //       console.log(this.cateList[this.active].id);
    //       this.init()
    //   }
    onLoad() {
      this.cateList[this.active].pageIndex++;
      // setTimeout(() => {
        this.init();
      // }, 2000);
    },
    // 下拉刷新
    onRefresh() {
      // 重置页码
      this.cateList[this.active].pageIndex = 1;
      // 清空数据
      this.cateList[this.active].postList.length = 0;
      // 发起请求
      this.init();
      // 重置finished
      this.cateList[this.active].finished = false;
    }
  
  },
  watch: {
    active() {
      if(this.cateList[this.active].postList.length === 0) this.init();
    }
  }
};
</script>

<style lang="less" scoped>

.head {
  width: 100%;
  height: 55px;
  background-color: #d43d3d;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
  .logo .iconnew {
    font-size: 60px;
    color: #fff;
    padding: 0 10px;
  }
  .search {
    flex: 1;
    height: 40px;
    background-color: rgba(255, 255, 255, 0.5);
    border-radius: 20px;
    text-align: center;
    line-height: 44px;
    font-size: 18px;
    > span {
      padding-left: 10px;
    }
  }
  .user {
    padding: 0 10px;
    font-size: 18px;
  }
}

/deep/.van-sticky {
  padding-right: 50px;
&::after {
  content: "+";
    position: absolute;
    width: 51px;
    height: 44px;
    background-color: #fff;
    color: #333;
    top: 0;
    right: 0;
    text-align: center;
    line-height: 42px;
    font-size: 35px;
   
}

}
</style>